package com.tencent.qf.web.config;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static springfox.documentation.builders.RequestHandlerSelectors.basePackage;

/***
 * @MethodName swagger 配置
 * @Description
 * @Author p_htaozhou@tencent.com
 * @Date 2022/9/7 11:49
 */

@Configuration
@EnableSwagger2
@ConditionalOnClass({Docket.class, ApiInfoBuilder.class})
@ConditionalOnProperty(prefix = "tdw.swagger", value = "enable", matchIfMissing = true)
@EnableConfigurationProperties(SwaggerProperties.class)
@Profile({"dev", "uat"})
public class SwaggerAutoConfiguration {

    @Bean
    public Docket createRestApi(SwaggerProperties properties) {
        List<Parameter> pars = getParameters();
        Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo(properties));
        ApiSelectorBuilder selector = docket.select();
        // api接口包扫描路径
        List<Predicate<RequestHandler>> list = this.buildPackage();
        if (list.isEmpty()) {
            // 未配置，默认一个不存在的路径，避免扫描整个项目路径
            selector.apis(basePackage(properties.getBasePackage()));
        } else if (list.size() == 1) {
            selector.apis(list.get(0));//
        } else {
            selector.apis(Predicates.or(list));
        }
        //
        selector.paths(PathSelectors.any())// 可以根据url路径设置哪些请求加入文档，忽略哪些请求
                .build().globalOperationParameters(pars);
        return docket;
    }

    public static List<Parameter> getParameters() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        tokenPar.name("token").description("系统登录凭证").modelRef(new ModelRef("String")).parameterType("header").required(false);
        List<Parameter> pars = new ArrayList<>();
        pars.add(tokenPar.build());
        return pars;
    }

    private List<Predicate<RequestHandler>> buildPackage() {
        List<Predicate<RequestHandler>> result = new ArrayList<>();
        String value = System.getProperties().getProperty("swagger-api-package");
        if (value == null || value.trim().equals("")) {
            return result;
        }
        String[] packageArr = value.split(";");
        for (String str : packageArr) {
            if (str == null || str.trim().equals("")) {
                continue;
            }
            result.add(RequestHandlerSelectors.basePackage(str));
        }
        return result;
    }

    // ========== apiInfo ==========

    /**
     * API 摘要信息
     */
    private static ApiInfo apiInfo(SwaggerProperties properties) {
        return new ApiInfoBuilder()
                .title(properties.getTitle())
                .description(properties.getDescription())
                .contact(new Contact(properties.getAuthor(), null, null))
                .version(properties.getVersion())
                .build();
    }

}
